<template>
  <a-modal
    :width="500"
    :visible="visible"
    :title="title"
    @cancel="onClose"
    @ok="onSubmit"
    ok-text="确定"
    :destroyOnClose="true"
    :confirmLoading="loading"
  >
    <a-spin :spinning="spinning">
      <a-form layout="vertical">
        <a-row :wrap="true" :gutter="12">
          <a-col :span="24" v-if="editType == 'group'">
            <a-form-item label="分组名称" v-bind="validateInfos.name">
              <a-input
                placeholder="请输入分组名称"
                v-model:value="formData.name"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="editType == 'tag'">
            <a-form-item label="选择分组" v-bind="validateInfos.pid">
              <a-select
                v-model:value="formData.pid"
                :options="groupOptions"
                placeholder="请选择分组"
                :allowClear="true"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="标签名称" v-bind="!id ? validateInfos.tag : validateInfos.name">
              <a-select
                v-if="!id"
                v-model:value="formData.tag"
                mode="tags"
                style="width: 100%"
                placeholder="请输入标签名，按回车键可输入多个标签名"
                :options="[]"
                :open="false"
              ></a-select>
              <a-input
                v-else
                placeholder="请输入标签名称"
                v-model:value="formData.name"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>

  </a-modal>

</template>
<script>
import { defineComponent, reactive, toRefs, computed, watch, nextTick } from "vue";
import { Form, message } from "ant-design-vue";
import store from "../../../../store";
import request from "../../../../common/utils/request";
const useForm = Form.useForm;
import _ from "lodash";
export default defineComponent({
  name: "EditTags",
  props: {
    id: {
      type: [Number, String],
      default: 0,
    },
    currentGroupId: {
      type: [Number, String],
      default: 0,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    editType: {
      type: String,
      default: '',
    },
    editInfo: {
      type: Object,
      default: () => ({}),
    }
  },
  components: {  },
  setup(props, { emit }) {
    const state = reactive({
      spinning: false,
      loading: false,
      groupOptions: [],
      ruleRef: {
        name: [{ required: false, message: "必填" }],
        tag: [{ required: false, message: "必填" }],
        pid: [{ required: false, message: "必选" }],
      }
    });

    const formData = reactive({
      name: "",
      tag: undefined, // 标签
      pid: undefined,
    });

    const title = computed(() => {
      return `${props.id ? '编辑' : '添加'}${props.editType == 'group' ? '分组' : '标签'}`
    });


    const { resetFields, validate, validateInfos} = useForm(formData, state.ruleRef);

    const onSubmit = () => {
      validate().then(() => {
        let params = {};
        for (let key in formData) {
          if (formData[key] || formData[key] === 0) {
            params[key] = formData[key];
          }
        }
        state.loading = true;
        if (props.id) {
          params.id = props.id;
        }
        let url = props.editType == 'group' ? '/business/customerTag/addGroup' : '/business/customerTag';
        let requestType = props.id ? 'put' : 'post';
        request[requestType]("/org", url, params).then((res) => {
          message.success(res.msg || props.id ? "编辑成功!" : '添加成功!');
          emit("success", props.editType);
        }).finally(() => {
          state.loading = false;
        });
      });
    };



    const onClose = () => {
      emit("handleCancel");
    };

    const setModelRef = (state) => {
      for (let key in state) {
        formData[key] = state[key];
      }
    };

    const init = () => {
      // 三种情况 （新增标签-编辑标签-新增分组）
      nextTick(() => {
        if (props.id) {
          // 编辑
          state.ruleRef.tag[0].required = false;
          state.ruleRef.pid[0].required = true;
          state.ruleRef.name[0].required = true;
        } else {
          // 新增
          state.ruleRef.name[0].required = props.editType === 'group';
          state.ruleRef.tag[0].required = true;
          state.ruleRef.pid[0].required = props.editType === 'tag';
        }
      })
      if (props.editType == 'group') return;
      // 编辑 标签
      state.spinning = true;
      request
        .get("/org", "/business/customerGroupTag", {})
        .then((res) => {
          state.groupOptions = res?.list.map((v) => {
            return {
              value: v.id,
              label: v.name,
            }
          })
          if (props.id) {
            setModelRef({
              name: props.editInfo?.name,
              pid: props.editInfo?.pid,
            })
          } else {
            formData.pid = props?.currentGroupId || undefined;
          }
        })
        .finally(() => {
          state.spinning = false;
        });
    };


    const reset = () => {
      state.groupOptions = [];
      state.loading = false;
      state.spinning = false;
    };


    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetFields();
          reset();
        }
      },
    );

    return {
      ...toRefs(state),
      formData,
      validateInfos,
      title,
      onClose,
      onSubmit,
    };
  },
});
</script>

<style lang="less" scoped>
p {
  &:last-of-type {
    margin-bottom: 0;
  }
}
.user-tag :deep(.ant-tag) {
  border-radius: 20px !important;
  padding: 0 12px 0 0 !important;
  background: #f1f1f1;
  border: none;
}
</style>
